package com.lyl.controller;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lyl.domain.User;
import com.lyl.domain.UserAuthAuditRecord;
import com.lyl.domain.UserAuthInfo;
import com.lyl.dto.UserDto;
import com.lyl.feign.UserServiceFeign;
import com.lyl.model.AuthForm;
import com.lyl.model.Result;
import com.lyl.service.UserAuthAuditRecordService;
import com.lyl.service.UserAuthInfoService;
import com.lyl.service.UserService;
import com.lyl.vo.UserAuthInfoVo;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author lylbell
 * @date 2021-06-26 14:46
 */

@RestController
@Api(tags = "用户管理")
@RequestMapping("/users")
public class UserController implements UserServiceFeign {

    @Autowired
    private UserService userService;


    @Autowired
    private UserAuthInfoService userAuthInfoService;

    @Autowired
    private UserAuthAuditRecordService userAuthAuditRecordService;




    @GetMapping
    @ApiOperation(value="分页查找")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current",value = "当前页"),
            @ApiImplicitParam(name = "size",value = "当前页"),
            @ApiImplicitParam(name = "mobile",value = "手机号"),
            @ApiImplicitParam(name = "userId",value = "用户id"),
            @ApiImplicitParam(name = "userName",value = "用户名"),
            @ApiImplicitParam(name = "realName",value = "真实姓名"),
            @ApiImplicitParam(name = "status",value = "状态"),
    })
    @PreAuthorize("hasAuthority('user_query')")
    public Result<Page<User>> findByPage(@ApiIgnore Page<User> page, String mobile, Long userId, String userName, String realName, Integer status) {
        page.addOrder(OrderItem.desc("last_update_time"));
        Page<User> userPage = userService.findByPage(page,mobile,userId,userName,realName,status,null);
        return Result.ok(userPage);
    }


    @GetMapping("/info")
    @ApiOperation(value="查询用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "用户id")
    })
    public Result<User> geById(Long id) {
        User user = userService.getById(id);
        return Result.ok(user);
    }


    @GetMapping("/directInvites")
    @ApiOperation(value="用户邀请列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current",value = "当前页"),
            @ApiImplicitParam(name = "size",value = "当前页"),
            @ApiImplicitParam(name = "userId",value = "用户id")
    })
    public Result<Page<User>> findDirectInvites(@ApiIgnore Page<User> page,Long userId) {
        Page<User> userPage = userService.findDirectInvites(page,userId);
        return Result.ok(userPage);
    }



    @GetMapping("/auths")
    @ApiOperation(value="分页查找高级认证实名审核")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current",value = "当前页"),
            @ApiImplicitParam(name = "size",value = "当前页"),
            @ApiImplicitParam(name = "mobile",value = "手机号"),
            @ApiImplicitParam(name = "userId",value = "用户id"),
            @ApiImplicitParam(name = "userName",value = "用户名"),
            @ApiImplicitParam(name = "realName",value = "真实姓名"),
            @ApiImplicitParam(name = "reviewsStatus",value = "审核状态"),
    })
//    @PreAuthorize("hasAuthority('user_query')")
    public Result<Page<User>> findByAuthPage(@ApiIgnore Page<User> page, String mobile, Long userId, String userName, String realName, Integer reviewsStatus) {
        page.addOrder(OrderItem.desc("last_update_time"));
        Page<User> userPage = userService.findByPage(page,mobile,userId,userName,realName,null,reviewsStatus);
        return Result.ok(userPage);
    }


    @GetMapping("/auth/info")
    @ApiOperation(value = "查看高级实名认证审核信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "用户的id")
    })
    public Result<UserAuthInfoVo> findByAuthId(Long id) {
        User user = userService.getById(id);
        List<UserAuthAuditRecord> userAuthAuditRecordList = null;
        List<UserAuthInfo> userAuthInfoList = null;
        if (user != null) {
            Integer reviewsStatus = user.getReviewsStatus();//用户的审核状态
            if (reviewsStatus == null || reviewsStatus == 0) {
                userAuthAuditRecordList = Collections.emptyList();//没有审核记录
                userAuthInfoList = userAuthInfoService.getAuthInfoByUserId(id);
            }else {
                userAuthAuditRecordList = userAuthAuditRecordService.getUserAuthAuditRecordList(id);//查询审核记录，只查最近三条即可
                //通过最近一条被审核的记录的authCode,去查认证信息
                UserAuthAuditRecord userAuthAuditRecord = userAuthAuditRecordList.get(0);
                Long authCode = userAuthAuditRecord.getAuthCode();
                userAuthInfoList = userAuthInfoService.getAuthInfoByAuthCode(authCode);
            }
        }
        return Result.ok(new UserAuthInfoVo(user,userAuthAuditRecordList,userAuthInfoList));
    }


    @PostMapping("/auths/status")
    @ApiOperation(value="审核认证信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "用户的id"),
            @ApiImplicitParam(name = "authStatus",value = "用户的审核状态"),
            @ApiImplicitParam(name = "authCode",value = "一组图片的唯一标识"),
            @ApiImplicitParam(name = "remark",value = "审核拒绝的原因"),
    })
    public Result updateUserAuthStatus(@RequestParam(required = true) Long id, @RequestParam(required = true) Integer authStatus,@RequestParam(required = true)  Long authCode, String remark) {
        Boolean update = userService.updateUserAuthStatus(id,authStatus,authCode,remark);
        if (update) {
            return Result.ok();
        }
        return Result.fail("审核失败");
    }


    @GetMapping("/current/info")
    @ApiOperation(value="获取当前正在登录的用户")
    public Result<User> getCurrentUser() {
        String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        User user = userService.getById(Long.valueOf(userId));
        user.setPassword("******");
        user.setPaypassword("******");
        return Result.ok(user);
    }


    @PostMapping("/authAccount")
    @ApiOperation(value="身份认证")
    @ApiImplicitParam(name = "authForm",value = "身份认证相关")
    public Result authAccount(@RequestBody AuthForm authForm) {
       Boolean isOk =  userService.authAccount(authForm);
       if (isOk) {
           return Result.ok("认证成功");
       }
       return Result.ok("认证失败");
    }




    /**
     * 用户高级认证
     */


    /**
     * 用于admin-server 里面远程调用member-server
     *
     * @param ids
     * @return
     */
    @Override
    public Map<Long,UserDto> getBasicUsers(List<Long> ids,String username,String mobile) {
        Map<Long,UserDto> userDtos = userService.getBasicUsers(ids,username,mobile);
        return userDtos;
    }
}
